import { EditModal } from '@ycx/ui';
import { useTheme } from '@/store/settingsStore.ts';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { App, Form, Input } from 'antd';
import { useRefreshUserInfo, useUserId, useUserInfo } from '@/store/userStore.ts';
import { useMutation } from '@tanstack/react-query';
import AccountServices from '@/api/services/accountServices.ts';
import UploadImage from '@/components/UploadImage';
import { isValidPhone } from '@/utils';

export type PersonalInfoModalRef = {
  open: () => void;
};

const PersonalInfoModal = forwardRef<PersonalInfoModalRef>((_props, ref) => {
  const { message } = App.useApp();
  const theme = useTheme();
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const userId = useUserId();
  const userInfo = useUserInfo();
  const refreshUserInfo = useRefreshUserInfo();

  const { mutate, isPending } = useMutation({
    mutationFn: AccountServices.update,
    onSuccess: async () => {
      message.success('修改个人信息成功');
      close();
      refreshUserInfo();
    },
    onError: (error) => {
      message.error(error.message);
    },
  });

  const close = () => {
    setOpen(false);
    form.resetFields();
  };

  const handleSubmit = async () => {
    await form.validateFields();
    const data = form.getFieldsValue();
    mutate({
      id: userId!,
      headImage: data.headImage[0].url.split('https://oss.uconcern.com/')[1],
      realName: data.realName,
      phone: data.phone,
    });
  };

  useEffect(() => {
    if (!open) return;
    form.setFieldsValue({
      headImage: [
        {
          uid: 1,
          name: userInfo?.headImage,
          status: 'done',
          url: userInfo?.headImage
            ? `https://oss.uconcern.com/${userInfo?.headImage}`
            : 'https://oss.uconcern.com/2024-10-28/开发/7086515189870592avatar.png',
        },
      ],
      realName: userInfo?.realName,
      phone: userInfo?.phone,
    });
  }, [open]);

  useImperativeHandle(ref, () => ({
    open: () => {
      setOpen(true);
    },
  }));

  return (
    <EditModal
      theme={theme}
      title="个人中心"
      open={open}
      onClose={close}
      onCancel={close}
      forceRender
      onOk={handleSubmit}
      confirmLoading={isPending}
      modalRender={(dom) => (
        <Form form={form} layout="vertical">
          {dom}
        </Form>
      )}
    >
      <Form.Item label="头像" name="headImage">
        <UploadImage maxCount={1} />
      </Form.Item>
      <Form.Item label="姓名" name="realName" rules={[{ required: true }]}>
        <Input></Input>
      </Form.Item>
      <Form.Item
        label="电话"
        name="phone"
        required={false}
        rules={[
          {
            validator: (_r, value) => {
              return isValidPhone(value) ? Promise.resolve() : Promise.reject('请输入正确的手机号');
            },
            validateTrigger: 'change',
          },
        ]}
      >
        <Input></Input>
      </Form.Item>
    </EditModal>
  );
});

export default PersonalInfoModal;
